package com.newbingo.quartz;

import java.util.Date;
import java.util.List;
import com.newbingo.entity.GameTable;
import com.newbingo.entity.PeriodGame;
import com.newbingo.service.imple.IGameTableService;
import com.newbingo.service.imple.IPeriodGameService;

/**
 * 生成最新一期游戏的bean
 * 
 * @author ChansonYan
 */
public class NewPeriodGameQuartz {
	private IPeriodGameService periodGameService = null;
	private IGameTableService gameTableService = null;
	private Integer gtno;
	//每期游戏时间间隔，单位为分钟
	private Integer timeInterval;

	/*
	 * 自动生成下一期游戏方法
	 */
	public void createLastestPeriodGame() {
		// 根据游戏桌号获取游戏桌实体和当前期数
		GameTable gameTable = gameTableService.findByGameTableId(gtno);
		PeriodGame periodGame;
		periodGame = periodGameService.getCurrentPeriodGame(gtno);
		// 游戏桌为在运行时，可以自动生成下一期游戏
		if (gameTable.getStatus().equals("running")) {
			// 如果本期游戏官方开奖时间小于当前时间，表示可以生成下一期游戏，否则表示上期未开奖，不生成下一期
			if (periodGame.getPeriodTime().before(new Date())) {
				PeriodGame newPeriodGame = new PeriodGame();
				newPeriodGame.setGameTable(gameTable);
				newPeriodGame.setIsDraw(0);
				// 计算出下一期游戏的官方期数
				newPeriodGame.setPgnum(periodGame.getPgnum() + 1);
				//计算下一期游戏的官方开奖时间
				//当本期官方开奖时间加上每期游戏时间间隔大于当前时间小于当前时间+时间间隔，表示官方开奖是连续的、未出现异常情况，或者此游戏是当天的，未有天数相隔
				//否则，计算上期和这期的时间间隔
				long timeLong=new Date().getTime()-periodGame.getPeriodTime().getTime();
				//计算出当前时间-本期游戏时间后除以时间间隔的倍数和余数
				int countTime=(int)(timeLong/(timeInterval*60*1000));
				int remainder=(int)(timeLong%(timeInterval*60*1000));
				Date newPeriodGameTime=new Date();
				if(countTime<=1){
					newPeriodGameTime.setTime(periodGame.getPeriodTime().getTime()+timeInterval*60*1000);
				}else{
					//若余数大于0，则倍数+1
					if(remainder>0){
						countTime++;	
					}
					newPeriodGameTime.setTime(periodGame.getPeriodTime().getTime()+countTime*timeInterval*60*1000);
				}
				newPeriodGame.setPeriodTime(newPeriodGameTime);
				periodGameService.save(newPeriodGame);
				gameTable.setCurrentPeriodGame(newPeriodGame);
				gameTableService.merge(gameTable);
			}
		}
	}

	public Integer getGtno() {
		return gtno;
	}

	public void setGtno(Integer gtno) {
		this.gtno = gtno;
	}

	public Integer getTimeInterval() {
		return timeInterval;
	}

	public void setTimeInterval(Integer timeInterval) {
		this.timeInterval = timeInterval;
	}

	public IPeriodGameService getPeriodGameService() {
		return periodGameService;
	}

	public void setPeriodGameService(IPeriodGameService periodGameService) {
		this.periodGameService = periodGameService;
	}

	public IGameTableService getGameTableService() {
		return gameTableService;
	}

	public void setGameTableService(IGameTableService gameTableService) {
		this.gameTableService = gameTableService;
	}

}
